import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Main {
    public static void main(String[] args) {

        // 创建Chrome浏览器选项
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");

        WebDriver driver = new ChromeDriver(options);

        try {
            // 打开网站
            driver.get("http://43.143.18.198:8080/login.html");

            // 查找用户名输入框并输入用户名
            WebElement usernameField = driver.findElement(By.id("username"));
            usernameField.sendKeys("hans");

            // 查找密码输入框并输入密码
            WebElement passwordField = driver.findElement(By.id("password"));
            passwordField.sendKeys("123");

            // 点击登录按钮
            WebElement loginButton = driver.findElement(By.id("submit"));
            loginButton.click();

            // 等待 alert 弹框出现，并点击
            WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.alertIsPresent());

            Alert alert = driver.switchTo().alert();
            alert.accept();


            // 查找名为“lisa”的会话
            WebElement lisaChat = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@message_session_id='5']")));
            lisaChat.click();

            // 查找消息输入框并输入“halo”信息
            WebElement messageInput = driver.findElement(By.cssSelector(".right .message_input"));
            messageInput.sendKeys("halo2");

            // 点击发送按钮
            WebElement sendButton = driver.findElement(By.xpath("//button[text()='发送']"));
            sendButton.click();

            System.out.println("消息已发送！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
